#pragma once
#include <iostream>
#include <string>
#include <filesystem>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "Mutex.hpp"

namespace ns_log
{
    enum class LogLevel
    {
        INFO,
        DEBUG,
        WARNING,
        ERROR,
        FATAL
    };

    std::string Level2String(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::INFO:
            return "INFO";
            break;
        case LogLevel::DEBUG:
            return "DEBUG";
            break;
        case LogLevel::WARNING:
            return "WARNING";
            break;
        case LogLevel::ERROR:
            return "ERROR";
            break;
        case LogLevel::FATAL:
            return "FATAL";
            break;
        default:
            return std::string();
            break;
        }
    }

    std::string GetCurrentTime()
    {
        // 获取时间戳
        time_t curr = time(nullptr);
        struct tm tm;
        localtime_r(&curr, &tm);

        char timebuff[64];
        snprintf(timebuff, sizeof(timebuff), "%4d-%02d-%02d %02d:%02d:%02d",
                 tm.tm_year + 1900,
                 tm.tm_mon + 1,
                 tm.tm_mday,
                 tm.tm_hour,
                 tm.tm_min,
                 tm.tm_sec);
        return timebuff;
    }

    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &logmessage) = 0;
    };

    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ~ConsoleLogStrategy() override {}
        void SyncLog(const std::string &logmessage) override
        {
            {
                LockGuard lockguard(&_lock);
                std::cout << logmessage << std::endl;
            }
        }

    private:
        Mutex _lock;
    };

    const static std::string logdefaultdir = "log";
    const static std::string logfilename = "log.txt";
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(std::string dir_path_name = logdefaultdir, std::string filename = logfilename)
            : _dir_path_name(dir_path_name), _file_name(filename)
        {
            // 目录操作属于访问临界资源
            {
                LockGuard lockguard(&_lock);
                if (std::filesystem::exists(_dir_path_name))
                {
                    return;
                }
                try
                {
                    std::filesystem::create_directories(_dir_path_name);
                }
                catch (const std::filesystem::filesystem_error &e)
                {
                    std::cerr << e.what() << std::endl;
                }
            }
        }
        void SyncLog(const std::string &logmessage)
        {
            // 文件操作属于临界资源
            {
                // log/log.txt
                LockGuard lockguard(&_lock);
                std::string target = _dir_path_name;
                target += "/";
                target += _file_name;
                // 写到文件
                std::ofstream out(target.c_str(), std::ios::app); // 追加方式打开
                if (!out.is_open())
                {
                    std::cout << "open file: " << target.c_str() << " error" << std::endl;
                    return;
                }
                out << logmessage;
                out << "\n";
                out.close();
            }
        }
        ~FileLogStrategy() override {}

    private:
        std::string _dir_path_name;
        std::string _file_name;
        Mutex _lock;
    };

    class Logger
    {
    public:
        Logger() {}

        void EnableConsoleStrategy()
        {
            _logstategy = std::make_unique<ConsoleLogStrategy>();
        }

        void EnableFileStrategy()
        {
            _logstategy = std::make_unique<FileLogStrategy>();
        }

        // 创建一个内部类，利用其生命周期，和能访问外部类的特性
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, std::string filename, ssize_t line, Logger &logger)
                : _level(Level2String(level)),
                  _filename(filename),
                  _curtime(GetCurrentTime()),
                  _pid(getpid()),
                  _line(line),
                  _owner(logger)
            {
                std::stringstream ss;
                ss << "[" << _curtime << "]";
                ss << " [" << _level << "]";
                ss << " [" << _pid << "]";
                ss << " [" << _filename << "]";
                ss << " [" << _line << "]";
                ss << " - ";
                _logmessage = ss.str();
            }

            // 细节，这里一定是引用，因为当前对象没有销毁
            template <class T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss; // 将任何类型转换为string
                ss << info;
                _logmessage += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                // 析构时，将一条完整的日志信息刷新出去
                if (_owner._logstategy)
                {
                    _owner._logstategy->SyncLog(_logmessage);
                }
            }

        private:
            std::string _level;
            std::string _filename;
            std::string _curtime;
            pid_t _pid;
            ssize_t _line;
            Logger &_owner; // 回指，调用刷新策略刷新出去。
            // 注意Outer 和 Inner 互相包含，无法确定对象大小，所以内部类包含外部类必须引用或者指针
            std::string _logmessage;
        };

        // 构造一个LogMessage的匿名对象，一个operator对应一个LogMessage,存活时间为一行
        LogMessage operator()(LogLevel level, const std::string &filename, ssize_t line)
        {
            return LogMessage(level, filename, line, *this);
        }
        ~Logger() {}

    private:
        // 刷新策略
        std::unique_ptr<LogStrategy> _logstategy;
    };

    Logger logger; // 定义一个全局对象

#define LOG(level) logger(level, __FILE__, __LINE__)
#define EnableConsoleLogStrategy() logger.EnableConsoleStrategy()
#define EnableFileLogStrategy() logger.EnableFileStrategy()
}